from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from typing import List
from app.database import get_db
from app.models import MCPService, KnowledgeBase, User
from app.schemas import MCPServiceCreate, MCPServiceUpdate, MCPServiceResponse
from app.core.deps import get_current_active_user
from app.core.logging import logger

router = APIRouter(prefix="/mcp-services", tags=["mcp-services"])

@router.post("/", response_model=MCPServiceResponse)
async def create_mcp_service(
    mcp_service: MCPServiceCreate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建MCP服务"""
    logger.info(f"用户 {current_user.username} 创建MCP服务: {mcp_service.name}")
    
    # 验证知识库是否存在且属于当前用户
    result = await db.execute(
        select(KnowledgeBase)
        .where(KnowledgeBase.id == mcp_service.knowledge_base_id)
        .where(KnowledgeBase.user_id == current_user.id)
    )
    
    knowledge_base = result.scalar_one_or_none()
    if not knowledge_base:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Knowledge base not found or access denied"
        )
    
    db_mcp_service = MCPService(**mcp_service.dict())
    db.add(db_mcp_service)
    await db.commit()
    await db.refresh(db_mcp_service)
    
    logger.info(f"MCP服务创建成功: {mcp_service.name}")
    return db_mcp_service

@router.get("/", response_model=List[MCPServiceResponse])
async def get_mcp_services(
    knowledge_base_id: int = None,
    skip: int = 0,
    limit: int = 100,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取MCP服务列表"""
    logger.info(f"用户 {current_user.username} 获取MCP服务列表")
    
    query = select(MCPService).join(KnowledgeBase).where(KnowledgeBase.user_id == current_user.id)
    
    if knowledge_base_id:
        query = query.where(MCPService.knowledge_base_id == knowledge_base_id)
    
    query = query.offset(skip).limit(limit)
    result = await db.execute(query)
    
    mcp_services = result.scalars().all()
    return mcp_services

@router.get("/{mcp_service_id}", response_model=MCPServiceResponse)
async def get_mcp_service(
    mcp_service_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取指定MCP服务"""
    logger.info(f"用户 {current_user.username} 获取MCP服务 {mcp_service_id}")
    
    result = await db.execute(
        select(MCPService)
        .join(KnowledgeBase)
        .where(MCPService.id == mcp_service_id)
        .where(KnowledgeBase.user_id == current_user.id)
    )
    
    mcp_service = result.scalar_one_or_none()
    if not mcp_service:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="MCP service not found"
        )
    
    return mcp_service

@router.put("/{mcp_service_id}", response_model=MCPServiceResponse)
async def update_mcp_service(
    mcp_service_id: int,
    mcp_service_update: MCPServiceUpdate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新MCP服务"""
    logger.info(f"用户 {current_user.username} 更新MCP服务 {mcp_service_id}")
    
    result = await db.execute(
        select(MCPService)
        .join(KnowledgeBase)
        .where(MCPService.id == mcp_service_id)
        .where(KnowledgeBase.user_id == current_user.id)
    )
    
    mcp_service = result.scalar_one_or_none()
    if not mcp_service:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="MCP service not found"
        )
    
    # 更新字段
    update_data = mcp_service_update.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(mcp_service, field, value)
    
    await db.commit()
    await db.refresh(mcp_service)
    
    logger.info(f"MCP服务更新成功: {mcp_service_id}")
    return mcp_service

@router.delete("/{mcp_service_id}")
async def delete_mcp_service(
    mcp_service_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除MCP服务"""
    logger.info(f"用户 {current_user.username} 删除MCP服务 {mcp_service_id}")
    
    result = await db.execute(
        select(MCPService)
        .join(KnowledgeBase)
        .where(MCPService.id == mcp_service_id)
        .where(KnowledgeBase.user_id == current_user.id)
    )
    
    mcp_service = result.scalar_one_or_none()
    if not mcp_service:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="MCP service not found"
        )
    
    await db.delete(mcp_service)
    await db.commit()
    
    logger.info(f"MCP服务删除成功: {mcp_service_id}")
    return {"message": "MCP service deleted successfully"}